package cn.jesin.css.utils;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.SecureRandom;
import java.util.concurrent.CompletableFuture;

/**
 * @author 谷汉斌
 * @description 验证码工具类（参考：https://next.api.aliyun.com/api/Dysmsapi/2017-05-25/SendSms?lang=JAVAASYNC&params={%22SignName%22:%22%E7%AE%80%E4%BA%91%E7%A4%BECFS%22,%22TemplateCode%22:%22SMS_302606777%22,%22TemplateParam%22:%22%7B%5C%22code%5C%22%3A%5C%223333%5C%22%7D%22,%22PhoneNumbers%22:%2219574429159%22}&RegionId=cn-beijing-finance-1&tab=DEMO）
 * @createTime 2024/8/15 下午9:57
 */
@Component
public class VerificationCodeUtil {

    @Value("${aliyunInfo.accessKeyId}")
    private  String keyId;
    @Value("${aliyunInfo.accessKeySecret}")
    private  String keySecret;
    @Value("${aliyunInfo.sign}")
    private  String sign;
    @Value("${aliyunInfo.templateCode}")
    private  String templateCode;

    /**
     * 生成六位数验证码
     */
    private  String generateVerificationCode() {
        //生成六位数的验证码
        SecureRandom random = new SecureRandom();
        // 生成一个0到999999之间的随机整数
        int code = random.nextInt(1000000);
        // 将整数转换为六位字符串，不足六位前面补0
        return String.format("%06d", code);
    }

    /**
     * 发送验证码
     */
    public  String sendVerificationCode(String phoneNumber) {

        //这个类，用于提供静态的凭证
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(keyId)
                .accessKeySecret(keySecret)
                .build());

        try (AsyncClient client = AsyncClient.builder()
                .region("cn-beijing-finance-1")
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build()) {
            String code = generateVerificationCode();
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName(sign)
                    .templateCode(templateCode)
                    .templateParam("{\"code\":\"" + code + "\"}")
                    .phoneNumbers(phoneNumber)
                    .build();
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            SendSmsResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));
            return code;
        } catch (Exception ex) {
            return "";
        }
    }

}
